package com.lovegu.jvm;

import lombok.SneakyThrows;

import java.io.InputStream;

/**
 * @author 老顾
 * @title: SelfClassLoader
 * @projectName java-restudy
 * @email: 1437594522@qq.com
 * @date 2022/10/9 21:34
 */
public class SelfClassLoader {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        ClassLoader myClassLoader = new ClassLoader() {
//            @SneakyThrows
//            @Override
//            protected Class<?> findClass(String name) throws ClassNotFoundException {
//                String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
//                InputStream inputStream = getClass().getResourceAsStream(fileName);
//                byte[] bytes = new byte[inputStream.available()];
//                inputStream.read(bytes);
//                return defineClass(name, bytes, 0, bytes.length);
//            }
//        };
            @SneakyThrows
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
                InputStream inputStream = getClass().getResourceAsStream(fileName);
                if (inputStream == null){
                    return super.loadClass(name);
                }
                byte[] bytes = new byte[inputStream.available()];
                inputStream.read(bytes);
                return defineClass(name, bytes, 0, bytes.length);
            }
        };

        Object object = myClassLoader.loadClass("com.lovegu.jvm.SelfClassLoader").newInstance();
        System.out.println(object.getClass());
        System.out.println(object instanceof com.lovegu.jvm.SelfClassLoader);
    }
}
